<script setup>
import { ref ,reactive,onMounted} from 'vue'
import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore} from '@/stores/index'
// 选项卡状态
const activeTab = ref('login');
// 表单校验对象
// const userInfo = ref({
//   username: '',
//   password: ''
//   // agree: true
// })
// 表单引用
const loginFormRef = ref(null);
const registerFormRef = ref(null);

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
});

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '', // 新增手机号
  gender: 1, // 新增性别，0表示未知
  agree: false
});
// 密码可见性控制
const showLoginPassword = ref(false);
const showRegPassword = ref(false);
const showConfirmPassword = ref(false);

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ]
};

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (/^\d+$/.test(value)) {
          callback(new Error('账号不能全为数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d).{6,}$/,
      message: '至少包含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],

  // 新增性别验证规则
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  agree: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请先同意协议'));
        } else {
          callback();
        }
      }
    }
  ]
};

// 登录方法
const doLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      handleLogin(); // 将异步操作提取到独立函数
    } else {
        ElMessage.error('请填写正确的登录信息');
        return false;
      }
  });
};

// 登录逻辑
const router = useRouter()
const userStore = useUserStore()
// 独立登录函数
const handleLogin = async () => {
  try {
    const username=loginForm.username;
    const password=loginForm.password;
    await userStore.getUserInfo({username, password});
    // 存储（默认有效期：会话期）

    // 根据"记住我"选项操作
    if (loginForm.remember) {
      // 勾选时保存用户名
      Cookies.set('rememberedUsername', loginForm.username, { expires: 7 });
    } else {
      // 未勾选时清除之前保存的用户名
      Cookies.remove('rememberedUsername');
    }

    Cookies.set('username',username)
    Cookies.set('memberId',userStore.userInfo.memberId)
    ElMessage.success('登录成功');
    router.replace('/');
  } catch (error) {
    ElMessage.error('登录失败，请检查账号密码');
  }
};
// 注册方法
const doRegister = () => {
  registerFormRef.value.validate((valid) => {
    if (valid) {
      handleRegister();
    } else {
      ElMessage.error('请填写正确的注册信息');
      return false;
    }
  });
};

// 注册处理逻辑
const handleRegister = async () => {
  try {
    await userStore.registerUser(registerForm);
    ElMessage.success('注册成功');

    // 只在成功时执行以下操作
    activeTab.value = 'login';
    loginForm.username = registerForm.username;

    // 重置注册表单
    registerForm.username = '';
    registerForm.password = '';
    registerForm.phone = '';
    registerForm.gender = 1;
    registerForm.confirmPassword = '';
    registerForm.agree = false;

  } catch (error) {
    ElMessage.error('注册失败，当前账号已存在');
  }
};
// 页面加载时检查是否有记住的用户名
onMounted(() => {
  const rememberedUsername = Cookies.get('rememberedUsername');
  if (rememberedUsername) {
    loginForm.username = rememberedUsername;
    loginForm.remember = true;
  }
});
</script>

<template>
  <div>
    <header class="login-header">
      <div class="container m-top-20">
        <RouterLink class="entry" to="/">
          进入网站首页
          <i class="iconfont icon-angle-right"></i>
          <i class="iconfont icon-angle-right"></i>
        </RouterLink>
      </div>
    </header>
    <section class="login-section">
      <div class="form-container">
        <!-- 登录表单 -->
        <transition name="fade" mode="out-in">
          <div v-if="activeTab === 'login'">
            <div class="form-header">
              <h2>欢迎回来</h2>
              <p>请输入您的账号和密码进行登录</p>
            </div>

            <el-form
                label-position="top"
                status-icon
                ref="loginFormRef"
                :model="loginForm"
                :rules="loginRules"
            >
              <el-form-item label="账号" prop="username">
                <el-input
                    v-model="loginForm.username"
                    placeholder="请输入您的账号"
                >
                  <template #prefix>
                    <i class="fas fa-user"></i>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <div class="password-input">
                  <el-input
                      v-model="loginForm.password"
                      :type="showLoginPassword ? 'text' : 'password'"
                      placeholder="请输入您的密码"
                  >
                    <template #prefix>
                      <i class="fas fa-lock"></i>
                    </template>
                  </el-input>
                  <button class="password-toggle" @click.prevent="showLoginPassword = !showLoginPassword">
                    <i :class="showLoginPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                  </button>
                </div>
              </el-form-item>

              <el-form-item>
                <el-checkbox v-model="loginForm.remember">
                  记住我
                </el-checkbox>
<!--                <div style="float: right;">-->
<!--                  <router-link to="/forgot-password" style="color: #ff6b6b; font-size: 14px;">忘记密码?</router-link>-->
<!--                </div>-->
              </el-form-item>

              <el-button class="subBtn" @click="doLogin">登录</el-button>
            </el-form>

<!--            <div class="social-login">-->
<!--              <div class="social-btn wechat">-->
<!--                <i class="fab fa-weixin"></i>-->
<!--              </div>-->
<!--              <div class="social-btn qq">-->
<!--                <i class="fab fa-qq"></i>-->
<!--              </div>-->
<!--              <div class="social-btn weibo">-->
<!--                <i class="fab fa-weibo"></i>-->
<!--              </div>-->
<!--            </div>-->

            <div class="form-footer">
              还没有账号? <a @click="activeTab = 'register'">立即注册</a>
            </div>
          </div>
        </transition>

        <!-- 注册表单 -->
        <transition name="fade" mode="out-in">
          <div v-if="activeTab === 'register'">
            <div class="form-header">
              <h2>创建新账户</h2>
              <p>欢迎加入六六商城，请填写注册信息</p>
            </div>

            <el-form
                label-position="top"
                status-icon
                ref="registerFormRef"
                :model="registerForm"
                :rules="registerRules"
            >
              <el-form-item label="账号" prop="username">
                <el-input
                    v-model="registerForm.username"
                    placeholder="请设置您的账号"
                >
                  <template #prefix>
                    <i class="fas fa-user"></i>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <div class="password-input">
                  <el-input
                      v-model="registerForm.password"
                      :type="showRegPassword ? 'text' : 'password'"
                      placeholder="请设置您的密码"
                  >
                    <template #prefix>
                      <i class="fas fa-lock"></i>
                    </template>
                  </el-input>
                  <button class="password-toggle" @click.prevent="showRegPassword = !showRegPassword">
                    <i :class="showRegPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                  </button>
                </div>
              </el-form-item>

              <el-form-item label="确认密码" prop="confirmPassword">
                <div class="password-input">
                  <el-input
                      v-model="registerForm.confirmPassword"
                      :type="showConfirmPassword ? 'text' : 'password'"
                      placeholder="请再次输入密码"
                  >
                    <template #prefix>
                      <i class="fas fa-lock"></i>
                    </template>
                  </el-input>
                  <button class="password-toggle" @click.prevent="showConfirmPassword = !showConfirmPassword">
                    <i :class="showConfirmPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                  </button>
                </div>
              </el-form-item>
              <!-- 新增：手机号码 -->
              <el-form-item label="手机号码" prop="phone">
                <el-input
                    v-model="registerForm.phone"
                    placeholder="请输入您的手机号码"
                >
                  <template #prefix>
                    <i class="fas fa-phone"></i>
                  </template>
                </el-input>
              </el-form-item>

              <!-- 新增：性别选择 -->
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="registerForm.gender">
<!--                  <el-radio :label="0">未知</el-radio>-->
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="registerForm.agree">
                  我已阅读并同意 <a class="agreement-link" href="#">《隐私条款》</a> 和 <a class="agreement-link" href="#">《服务条款》</a>
                </el-checkbox>
              </el-form-item>

              <el-button class="subBtn" @click="doRegister">注册</el-button>
            </el-form>

            <div class="form-footer">
              已有账号? <a @click="activeTab = 'login'">立即登录</a>
            </div>
          </div>
        </transition>
      </div>
    </section>

    <footer class="login-footer">
      <div class="container">
        <p>
          <a href="javascript:;">关于我们</a>
          <a href="javascript:;">帮助中心</a>
          <a href="javascript:;">售后服务</a>
          <a href="javascript:;">配送与验收</a>
          <a href="javascript:;">商务合作</a>
          <a href="javascript:;">搜索推荐</a>
          <a href="javascript:;">友情链接</a>
        </p>
        <p>CopyRight &copy; 六六商城</p>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.login-header {
  background: #fff;
  border-bottom: 1px solid #e4e4e4;

  .container {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    max-width: 1240px;
    margin: 0 auto;
    padding: 0 20px;
  }


  .entry {
    width: 120px;
    margin-bottom: 38px;
    font-size: 16px;
    color: #666;
    text-decoration: none;

    i {
      font-size: 14px;
      color: $xtxColor;
      letter-spacing: -5px;
    }
  }
}
.login-section {
  /* 调整背景图片显示方式为全屏 */
  background: url('@/assets/images/login-bg.png') no-repeat center center;
  background-size: cover;
  position: relative;
  min-height: 40vh; /* 设置最小高度为视口高度 */
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  overflow: hidden;

  /* 左侧背景区域 */
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    //height: 60%;
    background: rgba(255, 255, 255, 0.7);
    z-index: 1;
  }

  .form-container {
    position: relative;
    z-index: 2;
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    padding: 40px 20px;
    display: flex;
    justify-content: flex-end;
  }

  /* 表单盒子 */
  .form-container > div {
    width: 400px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    padding: 30px;
    transition: all 0.3s ease;
  }
}

.form-header {
  text-align: center;
  margin-bottom: 30px;

  h2 {
    font-size: 24px;
    color: #333;
    margin-bottom: 10px;
  }

  p {
    font-size: 14px;
    color: #999;
  }
}

/* 密码输入框样式 */
.password-input {
  position: relative;
  width: 340px;
  .el-input {
    width: 100%;
  }

  .password-toggle {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: #999;
    cursor: pointer;
    font-size: 16px;
    padding: 5px;
    z-index: 10;

    &:hover {
      color: $xtxColor;
    }
  }
}

.social-login {
  display: flex;
  justify-content: center;
  margin: 20px 0;

  .social-btn {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 10px;
    cursor: pointer;
    transition: all 0.3s ease;

    i {
      font-size: 20px;
      color: white;
    }

    &.wechat {
      background: #07C160;
    }

    &.qq {
      background: #12B7F5;
    }

    &.weibo {
      background: #E6162D;
    }

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 5px 10px rgba(0,0,0,0.1);
    }
  }
}

.form-footer {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #666;

  a {
    color: $xtxColor;
    text-decoration: none;
    cursor: pointer;
    margin-left: 5px;

    &:hover {
      text-decoration: underline;
    }
  }
}

.subBtn {
  background: $xtxColor;
  width: 100%;
  color: #fff;
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
  margin-top: 10px;
  transition: all 0.3s;

  &:hover {
    opacity: 0.9;
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba($xtxColor, 0.3);
  }
}

.agreement-link {
  color: $xtxColor;
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}

/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-section {
    background-position: center;

    &::before {
      width: 100%;
      background: rgba(255, 255, 255, 0.9);
    }

    .form-container {
      justify-content: center;

      > div {
        width: 90%;
        max-width: 400px;
      }
    }
  }
}

@media (max-width: 480px) {
  .login-header {
    .container {
      flex-direction: column;
      align-items: center;
    }

    .logo {
      margin-bottom: 10px;
    }

    .entry {
      margin-bottom: 20px;
    }
  }

  .form-container > div {
    padding: 20px;
  }
}

.login-footer {
  padding: 30px 0 50px;
  background: #fff;
  text-align: center;

  p {
    color: #999;
    padding-top: 20px;
    margin: 5px 0;

    a {
      line-height: 1;
      padding: 0 10px;
      color: #999;
      display: inline-block;
      text-decoration: none;

      ~ a {
        border-left: 1px solid #ccc;
      }

      &:hover {
        color: $xtxColor;
      }
    }
  }
}
</style>